﻿//<TunynetCopyright>
//--------------------------------------------------------------
//<copyright>青岛拓宇网络科技有限公司 2005-2008</copyright>
//<version>V0.5</verion>
//<createdate>2008-2-23</createdate>
//<author>mazq</author>
//<email>mazq@Tunynet.com</email>
//<log date="2008-2-23">创建</log>
//--------------------------------------------------------------
//</TunynetCopyright>

using System;
using System.Collections.Generic;
using System.Text;
using Tunynet.QingdaoCustoms.Caching;
using Tunynet.QingdaoCustoms.Common;
using System.Collections.ObjectModel;
using ChinaCustoms.Qingdao.Workflow.Permissions;
using ChinaCustoms.Framework.DeluxeWorks.Library.OGUPermission;
using Tunynet.QingdaoCustoms.Data.Utils;

namespace ChinaCustoms.Qingdao.Workflow.Supports
{
    /// <summary>
    /// 工作项业务逻辑类
    /// </summary>
    public class WorkItems
    {
        /// <summary>
        /// 初始化活动相应的工作项
        /// </summary>
        /// <remarks>
        /// 创建活动时调用
        /// </remarks>
        /// <param name="activityInstanceInfo">活动实例</param>
        /// <param name="creatorUserName">工作项创建人UserName</param>
        /// <param name="previousWorkItemGuid">前一个工作项ID</param>
        /// <param name="subTask">工作项的所属子任务</param>
        /// <returns>成功创建的工作项个数</returns>
        internal static int InitializeWorkItems(ActivityInstanceInfo activityInstanceInfo, string creatorUserName, Guid previousWorkItemGuid, SubTaskInfo subTask)
        {
            int createdWorkItemCount = 0;

            IUser creator = ChinaCustomsPermissionWrapper.GetUser(creatorUserName);
            if (creator != null)
            {
                TaskInfo taskInfo = Tasks.GetTaskByWorkflowGuid(activityInstanceInfo.WorkflowGuid);
                ActivityPrototypeInfo currentActivityPrototype = ActivityPrototypes.GetActivityPrototype(activityInstanceInfo.PrototypeGuid);

                ActivityPrototypeInfo firstActivity = ActivityPrototypes.GetFirstActivityPrototypeOfMainFlow(activityInstanceInfo.WorkflowGuid);

                WorkItemType workItemType = WorkItemType.ApprovalAndNavigation;
                if (firstActivity.CodeName.Equals(activityInstanceInfo.CodeName, StringComparison.CurrentCultureIgnoreCase))
                {
                    workItemType = WorkItemType.StartTask;
                    currentActivityPrototype.RequiredUserNames = taskInfo.SponsorUserName;
                }

                //WorkItem执行人
                ReadOnlyCollection<IUser> executors = null;
                if ((activityInstanceInfo.AllowRedesignateExecutor || workItemType == WorkItemType.StartTask) && !string.IsNullOrEmpty(currentActivityPrototype.RequiredUserNames))
                {
                    string[] executorUserNames = null;
                    executorUserNames = currentActivityPrototype.RequiredUserNames.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                    List<IUser> executorList = new List<IUser>();

                    foreach (string userName in executorUserNames)
                    {
                        IUser _user = ChinaCustomsPermissionWrapper.GetUser(userName);
                        if (_user != null)
                            executorList.Add(_user);
                    }
                    executors = new ReadOnlyCollection<IUser>(executorList);
                }
                else
                {
                    string[] roleArray = null;
                    if (!string.IsNullOrEmpty(currentActivityPrototype.RequiredRoles.Trim()))
                    {
                        roleArray = currentActivityPrototype.RequiredRoles.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    }
                    string[] organizationIDArray = null;
                    if (subTask != null)
                    {
                        organizationIDArray = new string[] { subTask.OrganizationID.ToString() };
                    }
                    else
                    {
                        if (currentActivityPrototype.RequiredRelativeDepartment != RelativeDepartmentLevel.NotSet)
                        {
                            if (creator != null)
                            {
                                if (currentActivityPrototype.RequiredRelativeDepartment == RelativeDepartmentLevel.RelativeOneLevel)
                                {
                                    organizationIDArray = new string[1];
                                    if (creator.Parent != null)
                                    {
                                        organizationIDArray[0] = creator.Parent.ID;
                                    }
                                    else
                                    {
                                        organizationIDArray[0] = string.Empty;
                                    }
                                }
                                else if (currentActivityPrototype.RequiredRelativeDepartment == RelativeDepartmentLevel.RelativeTopLevel)
                                {
                                    organizationIDArray = new string[1];
                                    if (creator.TopOU != null)
                                    {
                                        organizationIDArray[0] = creator.TopOU.ID;
                                    }
                                    else
                                    {
                                        organizationIDArray[0] = string.Empty;
                                    }
                                }
                            }
                        }
                        else if (!string.IsNullOrEmpty(currentActivityPrototype.RequiredDepartmentIDs.Trim()))
                        {
                            organizationIDArray = currentActivityPrototype.RequiredDepartmentIDs.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        }
                    }
                    executors = new ReadOnlyCollection<IUser>(ChinaCustomsPermissionWrapper.GetUsers(taskInfo.ApplicationCodeName, roleArray, organizationIDArray));
                }


                foreach (IUser executor in executors)
                {
                    WorkItemInfo workItemInfo = new WorkItemInfo();
                    workItemInfo.WorkItemGuid = Guid.NewGuid();
                    workItemInfo.ActivityGuid = activityInstanceInfo.ActivityGuid;
                    workItemInfo.ActivityName = activityInstanceInfo.ActivityName;
                    workItemInfo.TaskGuid = taskInfo.TaskGuid;

                    if (subTask != null)
                        workItemInfo.SubTaskGuid = subTask.SubTaskGuid;

                    workItemInfo.WorkItemType = workItemType;
                    workItemInfo.Status = WorkItemStatus.Executing;

                    workItemInfo.CreatorUserName = creator.LogOnName;
                    workItemInfo.CreatorDisplayName = creator.DisplayName;
                    workItemInfo.CreatorFullPath = creator.FullPath;

                    workItemInfo.ExecutorUserName = executor.LogOnName;
                    workItemInfo.ExecutorDisplayName = executor.DisplayName;
                    workItemInfo.ExecutorFullPath = executor.FullPath;

                    switch (workItemType)
                    {
                        case WorkItemType.StartTask:
                            workItemInfo.WorkItemName = string.Format("{0}-启动工作流-{1}", activityInstanceInfo.ActivityName, executor.LogOnName);
                            break;
                        case WorkItemType.ApprovalAndNavigation:
                            workItemInfo.WorkItemName = string.Format("{0}-审批-{1}", activityInstanceInfo.ActivityName, executor.LogOnName);
                            break;
                        case WorkItemType.ApprovalForExitSubFlow:
                            workItemInfo.WorkItemName = string.Format("{0}-审批子流程-{1}", activityInstanceInfo.ActivityName, executor.LogOnName);
                            break;
                        default:
                            break;
                    }

                    workItemInfo.PreviousWorkItemGuid = previousWorkItemGuid;

                    BusinessDataProvider.Instance().CreateUpdateWorkItem(workItemInfo, DataProviderAction.Create);

                    createdWorkItemCount++;
                }

            }

            return createdWorkItemCount;

            //if (createdWorkItemCount == 0)
            //{
            //    //如果没有创建任何WorkItem则返回到上一活动
            //    ActivityPrototypeInfo previousActivityPrototype = ActivityPrototypes.GetPreviousActivityPrototype(activityInstanceInfo.WorkflowGuid, activityInstanceInfo.CodeName);
            //    ActivityInstanceInfo previousActivity = ActivityInstances.GetLastActivityByCodeName(activityInstanceInfo.WorkflowGuid,activityInstanceInfo.SubFlowGuid, previousActivityPrototype.CodeName);
            //    RedoWorkItemsOfActivity(previousActivity.ActivityGuid);
            //}
        }


        /// <summary>
        /// 创建工作项
        /// </summary>
        /// <param name="workItemInfo">工作项实体对象</param>
        public static void CreateWorkItem(WorkItemInfo workItemInfo)
        {
            BusinessDataProvider.Instance().CreateUpdateWorkItem(workItemInfo, DataProviderAction.Create);
        }


        /// <summary>
        /// 保存工作项
        /// </summary>
        public static void SaveWorkItem(WorkItemInfo workItemInfo)
        {
            BusinessDataProvider.Instance().CreateUpdateWorkItem(workItemInfo, DataProviderAction.Update);
        }

        /// <summary>
        /// 完成工作项
        /// </summary>
        public static void CompleteWorkItem(Guid workItemGuid, out bool activityIsComplete)
        {
            BusinessDataProvider.Instance().CompleteWorkItem(workItemGuid, out activityIsComplete);
        }

        ///// <summary>
        ///// 取消工作项
        ///// </summary>
        ///// <param name="taskID">TaskID</param>
        ///// <param name="activityGuid">ActivityGuid</param>
        ///// <param name="subFlowID">SubFlowID</param>
        ///// <param name="workItemType">WorkItemType</param>
        ///// <param name="excludeWorkItemID">排除的WorkItemID</param>
        //public static void CancelWorkItems(int taskID, Guid activityGuid, int subFlowID, WorkItemType? workItemType, int excludeWorkItemID)
        //{
        //    BusinessDataProvider.Instance().CancelWorkItems(taskID, activityGuid, subFlowID, workItemType, excludeWorkItemID);
        //}

        /// <summary>
        /// 删除工作项
        /// </summary>
        public static void DeleteWorkItem(Guid workItemGuid)
        {
            BusinessDataProvider.Instance().DeleteWorkItem(workItemGuid);
        }

        ///<overloads>获取工作项</overloads>
        /// <summary>
        /// 获取工作项
        /// </summary>
        public static WorkItemInfo GetWorkItem(Guid workItemGuid)
        {
            return BusinessDataProvider.Instance().GetWorkItem(workItemGuid);
        }


        /// <summary>
        /// 获取活动对应的一个工作项
        /// </summary>
        /// <param name="activityGuid">活动ID</param>
        /// <param name="subFlowID">子流程ID</param>
        /// <param name="workItemType">工作项类型</param>
        /// <param name="workItemStatus">工作项状态</param>
        /// <returns>WorkItemInfo</returns>
        public static WorkItemInfo GetOneWorkItemOfActivity(Guid activityGuid, WorkItemType? workItemType, WorkItemStatus workItemStatus)
        {
            return BusinessDataProvider.Instance().GetOneWorkItemOfActivity(activityGuid, workItemType, workItemStatus);
        }

        /// <summary>
        /// 获取活动对应的一个工作项
        /// </summary>
        /// <remarks>
        /// 获取WorkItemType=StartTask或者WorkItemType=ApprovalAndNavigation的工作项
        /// </remarks>
        /// <param name="activityGuid">活动ID</param>
        /// <param name="workItemStatus">工作项状态</param>
        /// <returns>WorkItemInfo</returns>
        public static WorkItemInfo GetOneWorkItemOfActivity(Guid activityGuid, WorkItemStatus workItemStatus)
        {
            return BusinessDataProvider.Instance().GetOneWorkItemOfActivity(activityGuid, null, workItemStatus);
        }

        /// <summary>
        /// 获取活动对应的多个符合条件的工作项
        /// </summary> 
        public static List<WorkItemInfo> GetAllWorkItemOfActivity(Guid activityGuid, WorkItemType? workItemType, WorkItemStatus workItemStatus)
        {
            return BusinessDataProvider.Instance().GetAllWorkItemOfActivity(activityGuid, workItemType, workItemStatus);
        }

        /// <summary>
        /// 获取活动对应的多个符合条件的工作项
        /// </summary> 
        public static List<WorkItemInfo> GetAllWorkItemOfActivity(Guid activityGuid, WorkItemStatus workItemStatus)
        {
            return BusinessDataProvider.Instance().GetAllWorkItemOfActivity(activityGuid, null, workItemStatus);
        }

        /// <summary>
        /// 获取Task中第一个工作项
        /// </summary>   
        public static WorkItemInfo GetFirstWorkItem(Guid taskGuid)
        {
            return BusinessDataProvider.Instance().GetFirstWorkItem(taskGuid);
        }

        /// <summary>
        /// 根据条件获取工作项
        /// </summary>
        /// <param name="taskGuid">TaskID</param>
        /// <param name="status">工作项状态</param>
        public static List<WorkItemInfo> GetWorkItems(Guid taskGuid, WorkItemStatus? status)
        {
            return BusinessDataProvider.Instance().GetWorkItems(null, taskGuid, status, null);
        }

        /// <summary>
        /// 根据条件获取工作项
        /// </summary>
        ///<param name="query">工作项条件</param>
        public static PagingDataSet<WorkItemInfo> GetWorkItems(WorkItemQuery query)
        {
            return BusinessDataProvider.Instance().GetWorkItems(query);
        }

        /// <summary>
        /// 获取用户待办事项
        /// </summary>
        /// <remarks>这个方法不再推荐使用.请使用GetWorkItems可以获取更加灵活的实现</remarks>
        public static List<WorkItemInfo> GetUserExecutingWorkItems(string applicationCodeName, string userName)
        {
            string cacheKey = string.Format("UserExecutingWorkItems:{0}", userName);
            List<WorkItemInfo> workItems = null;

            //workItems = WebCache.Get(cacheKey) as List<WorkItemInfo>;
            //if (workItems == null)
            //{
            workItems = new List<WorkItemInfo>();

            List<WorkItemInfo> originalWorkItems = BusinessDataProvider.Instance().GetWorkItems(applicationCodeName, null, WorkItemStatus.Executing, userName);
            foreach (WorkItemInfo workItem in originalWorkItems)
            {
                TaskInfo task = Tasks.GetTask(workItem.TaskGuid);
                //if ((task.ExecutingActivityInMainFlow.ActivityGuid == workItem.ActivityGuid) && (task.Status == TaskStatus.Executing))
                if (task.Status == TaskStatus.Executing)
                    workItems.Add(workItem);
            }

            //    WebCache.Insert(cacheKey, workItems, WebCache.MinuteFactor * 5);
            //}

            return workItems;
        }

        /// <summary>
        /// 获取后续工作项
        /// </summary>
        public static List<WorkItemInfo> GetNextWorkItems(Guid previousWorkItemGuid)
        {
            return BusinessDataProvider.Instance().GetNextWorkItems(previousWorkItemGuid);
        }

        /// <summary>
        /// 获取后续工作项
        /// </summary>
        public static List<WorkItemInfo> GetNextWorkItems(Guid previousWorkItemGuid,WorkItemStatus workItemStatus)
        {
            return BusinessDataProvider.Instance().GetNextWorkItems(previousWorkItemGuid,workItemStatus);
        }

        /// <summary>
        /// 获取所有曾经流转到的该活动原型分解的工作项的工作项
        /// </summary>
        /// <remarks>只获取同一SubTask的工作项</remarks>
        public static List<WorkItemInfo> GetPreviousWorkItemsToThisActivityPrototype(WorkItemInfo workItem)
        {
            return BusinessDataProvider.Instance().GetPreviousWorkItemsToThisActivityPrototype(workItem);
        }

        ///// <summary>
        ///// 获取活动的WorkItem
        ///// </summary>
        ///// <param name="activityGuid">活动ID</param>
        //public static List<WorkItemInfo> GetWorkItemsOfActivity(Guid activityGuid)
        //{
        //    return BusinessDataProvider.Instance().GetWorkItemsOfActivity(activityGuid);
        //}

        ///// <summary>
        ///// 获取SubFlow路径中的WorkItem
        ///// </summary>
        ///// <param name="subFlowID">子流程ID</param>
        //public static List<WorkItemInfo> GetWorkItemsOfSubFlowPath(int subFlowID)
        //{
        //    return BusinessDataProvider.Instance().GetWorkItemsOfSubFlowPath(subFlowID);
        //}


        /// <summary>
        /// 获取活动的执行人员
        /// </summary>
        /// <param name="activityGuid">活动ID</param>
        /// <returns>执行人员用户名集合</returns>
        public static List<string> GetExecutorsOfActivity(Guid activityGuid)
        {
            return BusinessDataProvider.Instance().GetExecutorsOfActivity(activityGuid);
        }


        ///// <summary>
        ///// 重新执行普通活动的所有工作项
        ///// </summary>
        //public static void RedoWorkItemsOfActivity(Guid activityGuid)
        //{
        //    BusinessDataProvider.Instance().RedoWorkItemsOfActivity(activityGuid);
        //}

        ///// <summary>
        ///// 重新执行子流程的所有工作项
        ///// </summary>
        //public static void RedoWorkItemsOfSubFlow(int subFlowID)
        //{
        //    BusinessDataProvider.Instance().RedoWorkItemsOfSubFlow(subFlowID);
        //}




    }
}
